package com.qf.myshop.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.myshop.entity.Cart;
import com.qf.myshop.entity.Product;
import com.qf.myshop.service.CartService;
import com.qf.myshop.service.impl.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/cart")
public class CartController  extends BaseServlet {
     CartService cartService = new CartServiceImpl();
    public  String show(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取页面传来的参数
        Integer uid = null;
        try{
            uid =  Integer.parseInt(req.getParameter("uid"));}
        catch (NumberFormatException e){

        }
        uid =3;
        List<Cart> list =cartService.list(uid);
        System.out.println(list);
        for(Cart c:list){
            Product p = cartService.findProductBypid(c.getPid());
            c.setProduct(p);
        }
        req.setAttribute("list",list);
        System.out.println(req.getAttribute("list"));
        return "forward:/cart.jsp";
    }
    public String delete(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException {
        Integer cid =null;
        try{
            cid =  Integer.parseInt(req.getParameter("cid"));}
        catch (NumberFormatException e){
        }
        boolean ret = cartService.delByCid(cid);
        //杰克逊将Java对象转换成JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(ret);
        return "forward:/cart?method=show";
    }
    public String clear(HttpServletRequest req,HttpServletResponse resp){
        //获取页面传来的参数
        Integer uid = null;
        try{
            uid =  Integer.parseInt(req.getParameter("uid"));}
        catch (NumberFormatException e){

        }
        uid =3;
        boolean ret = cartService.delByUid(uid);
        return "forward:/cart?method=show";
    }
    public String update(HttpServletRequest req,HttpServletResponse resp){
        //获取页面传来的参数
        Integer cid = null;
        Integer cnum = null;
        Double price = null;
        Double count = null;

        try{
            cid =  Integer.parseInt(req.getParameter("cid"));
            cnum  =  Integer.parseInt(req.getParameter("cnum"));
            price  =  Double.parseDouble(req.getParameter("price"));
        }
        catch (NumberFormatException e){
        }
        count= price *cnum;
        System.out.println(count);
        boolean ret = cartService.updateByCid(cid,cnum,count);
        return "forward:/cart?method=show";
    }

}
